package cn.ncist.health_service_provider.service.impl;

import cn.ncist.common.RespResult;
import cn.ncist.constant.MessageConstant;
import cn.ncist.health_interface.service.LoginService;
import cn.ncist.health_service_provider.dao.LoginMapper;
import cn.ncist.health_service_provider.dao.MemberMapper;
import cn.ncist.pojo.Member;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
@DubboService(interfaceClass = LoginService.class,timeout = 50000)
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public RespResult check(String email, String validateCode) {
        //验证用户的验证码是否输入正确
        String validateCodeInRedis = (String) redisTemplate.opsForValue().get(email + "validateCode");
        if(!validateCode.equals(validateCodeInRedis)){
            //验证码输入错误
            return new RespResult(false, MessageConstant.VALIDATECODE_ERROR);
        }else {
            //验证码输入正确
            //判断当前登录的用户是不是会员
            Member member = memberMapper.findMemberByTelephone(email);
            if(member == null){
                //当前登录用户不是会员
                //先注册再登录
                Member member_1 = new Member();
                member_1.setPhoneNumber(email);
                member_1.setRegTime(new Date());
                memberMapper.insert(member_1);
                //保存会员信息到Redis中
                redisTemplate.opsForSet().add(email,member_1);
            }
            //保存会员信息到Redis中
            redisTemplate.opsForSet().add(email,member);
        }
        return new RespResult(true,MessageConstant.LOGIN_SUCCESS);
    }
}
